<template>
  <div class="user-points-page">
    <van-nav-bar title="积分" left-arrow right-text="退出" @click-left="router.back()" @click-right="onExit" fixed />
    <div class="header"></div>
    <div class="user-card" v-if="userDetail">
      <img class="avatar" :src="userDetail.avatar" alt="avatar" />
      <div class="meta">
        <div class="name">{{ userDetail.nickName || userDetail.memoName || '未命名用户' }}</div>
        <div class="id">ID: {{ userDetail.userShowId }}</div>
      </div>
      <div class="score">
        <div class="value">{{ totalPoints }}</div>
        <div class="label">积分</div>
      </div>
    </div>

    <div class="sign-card">
      <div class="sign-left">
        <div class="sign-title">积分签到</div>
        <div class="stats">
          <div class="stat">
            <div class="stat-value">{{ totalPoints }}</div>
            <div class="stat-label">总积分</div>
          </div>
          <div class="divider" />
          <div class="stat">
            <div class="stat-value">{{ continuousDays }}</div>
            <div class="stat-label">连续天数</div>
          </div>
          <div class="divider" />
          <div class="stat">
            <div class="stat-value">{{ totalSignDays }}</div>
            <div class="stat-label">累计签到</div>
          </div>
        </div>
        <div class="last-time" v-if="lastSignTime">上次签到：{{ lastSignTime }}</div>
      </div>
      <div class="sign-right">
        <button class="sign-btn" :class="{ done: todaySigned }" @click="onSignButtonClick">
          {{ todaySigned ? '今日已签' : '立即签到' }}
        </button>
        <div class="sign-status" :class="statusType">{{ statusMessage }}</div>
      </div>
    </div>

    <div class="points-detail">
      <div class="detail-title">积分明细</div>
      <div v-if="records.length === 0" class="empty">暂无积分流水</div>
      <div v-else class="list">
        <div class="item" v-for="(item, idx) in records" :key="idx">
          <div class="left">
            <div class="name">{{ item.name }}</div>
            <div class="time">{{ item.time }}</div>
          </div>
          <div class="right" :class="{ plus: item.delta > 0, minus: item.delta < 0 }">
            {{ item.delta > 0 ? '+' : '' }}{{ item.delta }}
          </div>
        </div>
      </div>
    </div>

    <div class="tips">
      更多积分玩法，敬请期待～
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { useUserStore } from '@/stores/user';
import { appSigninDaysApi, appSigninApi, getUserSettingOtherApi } from '@/api/signin';

const userStore = useUserStore();
const router = useRouter();

const userDetail = ref(null);
const totalPoints = ref(0);
const todaySigned = ref(false);
const continuousDays = ref(0);
const totalSignDays = ref(0);
const lastSignTime = ref('');
const statusMessage = ref('');
const statusType = ref(''); // success / error
const records = ref([]); // 积分明细占位，暂无返回

const loadSignData = async () => {
  try {
    const res = await appSigninDaysApi({});
    if (res && (res.code === '10000' || res.success)) {
      const data = res.data || {};

      // 连续与累计天数
      continuousDays.value = Number(data.continueDays ?? data.continuityDays ?? 0);
      totalSignDays.value = Number(data.days ?? data.totalDays ?? 0);

      // 最近签到时间与“今日已签”判断
      if (data.lastTime) {
        const last = new Date(data.lastTime);
        lastSignTime.value = last.toLocaleString();
        const now = new Date();
        const sameDay = last.getFullYear() === now.getFullYear() &&
          last.getMonth() === now.getMonth() &&
          last.getDate() === now.getDate();
        todaySigned.value = sameDay;
      } else {
        lastSignTime.value = '';
        todaySigned.value = false;
      }

      // 积分明细（七天规则）
      const list = Array.isArray(data.scoreList) ? data.scoreList : [];
      records.value = list.map((it) => ({
        name: `第${it.days}天签到`,
        time: '',
        delta: Number(it.score || 0)
      }));
    }
  } catch (e) {
    // 静默失败
    console.error('加载签到信息失败:', e);
  }
};

const loadUserDetail = async () => {
  try {
    const uid = userStore?.userInfo?.userData?.id || userStore?.userId;
    if (!uid) return;
    const res = await getUserSettingOtherApi(uid);
    if (res && (res.code === 200 || res.success || res.code === '10000')) {
      const detail = res.data || {};
      userDetail.value = detail;
      const points = Number(detail.pointsBalance ?? detail.integral ?? detail.points ?? detail.score ?? 0);
      if (!Number.isNaN(points)) totalPoints.value = points;
    }
  } catch (e) {
    console.error('加载用户详情失败:', e);
  }
};

const onSignButtonClick = async () => {
  if (todaySigned.value) return;
  statusMessage.value = '正在签到...';
  statusType.value = '';
  try {
    const res = await appSigninApi({});
    if (res && (res.code === 200 || res.success || res.code === '10000')) {
      statusMessage.value = '签到成功！';
      statusType.value = 'success';
      await loadSignData();
      await loadUserDetail();
    } else {
      statusMessage.value = '签到失败';
      statusType.value = 'error';
    }
  } catch (e) {
    statusMessage.value = '签到失败，请稍后重试';
    statusType.value = 'error';
  }
};

onMounted(async () => {
  await loadUserDetail();
  await loadSignData();
});

// 不调用接口的本地退出：仅跳转登录页
const onExit = () => {
  // 可选择性地清理本地缓存/状态，这里只做跳转，避免调用任何接口
  router.push({ path: '/login' });
};
</script>

<style scoped lang="scss">
.user-points-page {
  background: #f6f7fb;
  height: 100%;
  padding: 14px;
  padding-bottom: 20px;
}

.header {
  height: 30px;


}

.user-card {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
    background: #f2f2f2;
  }

  .meta {
    color: #333;
    line-height: 1.2;

    .name {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 5px;
    }

    .id {
      font-size: 12px;
      color: #888;
    }
  }

  .score {
    margin-left: auto;
    text-align: right;

    .value {
      color: #333;
      font-size: 20px;
      font-weight: 700;
    }

    .label {
      font-size: 12px;
      color: #666;
    }
  }
}

.sign-card {
  margin-top: 12px;
  background: linear-gradient(135deg, #2563eb, #3b82f6);
  color: #fff;
  border-radius: 12px;
  padding: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 6px 14px rgba(37, 99, 235, 0.18);

  .sign-left {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .sign-title {
      font-size: 16px;
      font-weight: 600;
    }

    .stats {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .stat {
      text-align: center;

      .stat-value {
        font-size: 18px;
        font-weight: 700;
      }

      .stat-label {
        font-size: 12px;
        opacity: 0.9;
      }
    }

    .divider {
      width: 1px;
      height: 24px;
      background: rgba(255, 255, 255, 0.35);
    }

    .last-time {
      font-size: 12px;
      opacity: 0.9;
    }
  }

  .sign-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 6px;

    .sign-btn {
      min-width: 92px;
      padding: 8px 14px;
      border-radius: 999px;
      border: none;
      background: #fde68a;
      color: #92400e;
      font-weight: 600;
    }

    .sign-btn.done {
      background: rgba(255, 255, 255, 0.25);
      color: #fff;
    }

    .sign-status {
      font-size: 12px;
      min-height: 16px;
    }

    .sign-status.success {
      color: #bbf7d0;
    }

    .sign-status.error {
      color: #fecaca;
    }
  }
}

.points-detail {
  margin-top: 12px;
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .list {
    overflow: auto;
    max-height: 35vh;
    padding: 0 10px;
  }

  .detail-title {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #333;
  }

  .empty {
    text-align: center;
    font-size: 12px;
    color: #888;
    padding: 16px 0;
  }

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f4f6;
  }

  .item:last-child {
    border-bottom: none;
  }

  .left {
    display: flex;
    flex-direction: column;
  }

  .name {
    font-size: 13px;
    color: #333;
  }

  .time {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
  }

  .right {
    font-size: 14px;
    font-weight: 700;
  }

  .right.plus {
    color: #16a34a;
  }

  .right.minus {
    color: #ef4444;
  }
}

.tips {
  margin-top: 12px;
  text-align: center;
  font-size: 12px;
  color: #666;
}
</style>
